# -*- coding: utf-8 -*-
# @Time    : 2024/5/19 11:57
# @Author  : Alvin
# @File    : db_operation.py
from flask import Blueprint, jsonify,request
from ..utils.db_service import get_db
from datetime import datetime
from flask_jwt_extended import jwt_required, get_jwt_identity
utils_bp = Blueprint('utils',__name__)

@utils_bp.route('/get_all_tasks_record', methods=['GET'])
@jwt_required()
def get_all_tasks_record_by_user_id():
    try:
        db = get_db()
        username = get_jwt_identity()
        user_id = db.fetchone("select user_id from users where username = %s",(username,))['user_id']
        print(user_id)
        result = db.fetchall("select * from task_records where user_id = %s", (user_id,))
        if result:
            # 遍历结果集，对每个任务记录中的start字段进行处理
            for record in result:
                # 假设start字段是第二个字段，可以根据实际情况调整索引
                start_datetime_str = record['start_time'].strftime("%a, %d %b %Y %H:%M:%S")
                end_datetime = record['end_time']
                if end_datetime:
                    end_datetime_str = end_datetime.strftime("%a, %d %b %Y %H:%M:%S")
                    record['end_time'] = datetime.strptime(end_datetime_str, "%a, %d %b %Y %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S")
                record['start_time'] = datetime.strptime(start_datetime_str, "%a, %d %b %Y %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S")

        return jsonify({'status': 200, 'data': result}), 200
    except Exception as e:
        return jsonify({'status': 500, 'data': e}), 500
@utils_bp.route('/delete_task', methods=['GET'])
def delete_task_by_job_id():
    db = get_db()
    job_id = request.args.get('jobId')
    row = db.delete("task_records", 'task_id=%s',job_id)
    if row > 0:
        return jsonify({'status': 200, 'data': "删除成功!"}), 200
    return jsonify({'status': 500, 'data': "删除失败!"}), 500
@utils_bp.route('/get_keyword_recommendation', methods=['GET'])
def get_keyword_recommendation():
    db = get_db()
    # keyword = request.args.get('keyword')
    result = db.fetchall("SELECT keyword FROM keyword_notes")
    return jsonify({'status': 200, 'data': result})

